package com.reef.impl;


import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.reef.dao.TeacherRepository;
import com.reef.dto.ReaderDto;
import com.reef.entity.Reader;
import com.reef.service.TeacherService;
@Service
public class TeacherServiceImpl implements TeacherService{
	@Autowired
	private TeacherRepository tRepository;
	/**
	 * 老师多条件动态查询
	 */
	public Page<Reader> selTeacherAll(ReaderDto tDto,Pageable pageable) {
		Specification<Reader> spec = getSpec(tDto);
		return tRepository.findAll(spec, pageable);
	}
	/**
	 * 单独封装的方法
	 * @param tDto
	 * @return
	 */
	public Specification<Reader> getSpec(final ReaderDto tDto) {
		return new Specification<Reader>() {

			public Predicate toPredicate(Root<Reader> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
				//创建SQL表达式
				Predicate p = criteriaBuilder.conjunction();
				//声明表达式的集合
				List<Expression<Boolean>> list = p.getExpressions();
				if (tDto.getR_id()!=0 ) {
					list.add(criteriaBuilder.equal(root.get("r_id").as(int.class),tDto.getR_id() ));
				}
				if (tDto.getName()!=null && tDto.getName()!=" ") {
					list.add(criteriaBuilder.like(root.get("name").as(String.class), "%"+tDto.getName()+"%"));
				}
				if (tDto.getSection()!=null && tDto.getSection()!=" ") {
					list.add(criteriaBuilder.like(root.get("section").as(String.class), "%"+tDto.getSection()+"%"));
				}
				if (tDto.getStaus()!=0) {
					list.add(criteriaBuilder.equal(root.get("staus").as(Integer.class),tDto.getStaus() ));
				}
				return p;
			}
		};
	}
	public List<String> selSection() {
		// TODO Auto-generated method stub
		return tRepository.selSection();
	}
	public Reader insertTea(Reader reader) {
		// TODO Auto-generated method stub
		return tRepository.save(reader);
	}
	public Reader updateTea(Reader reader) {
		// TODO Auto-generated method stub
		return tRepository.save(reader);
	}

}
